<template>
  <div class="update-photo">
    <img class="img" :src="img" ref="img">

    <div class="toolbar">
      <div class="cancel" @click="$emit('close')">取消</div>
      <div class="confirm" @click="onConfirm">完成</div>
    </div>
  </div>
</template>

<script>
import { updateUserPhoto } from '@/api/user'
import 'cropperjs/dist/cropper.css';
import Cropper from 'cropperjs';
export default {
  name: 'UpdatePhoto',
  components: {},
  props: {
    // 预览图片地址信息  
    img: {
      type: [String, Object],
      required: true
    }
  },
  data () {
    return {}
  },
  mounted () {
    // 这是挂载成功了，存在真实的DOM节点
    this.cropper = new Cropper(this.$refs.img, {
      viewMode: 1,  // 视图模式，1是限制裁剪框不超过画布的大小
      dragMode: 'move',   // 拖动模式, move是移动画布
      aspectRatio: 1,  // 纵横比 
      cropBoxMovable: false,  // 裁剪框可移动
      cropBoxResizable: false, // 裁剪框可拖动缩放大小
      background: false  // 背景是否需要
    });
  },
  methods: {
      // 确定事件
      onConfirm(){
        // cropper.getCroppedCanvas() 调用的目的是返回一个裁剪的canvas对象
        // 裁剪的canvas对象.toBlob() 方法是将画布对象转化成 blob文件数据
        this.cropper.getCroppedCanvas().toBlob(async blob=>{
          // console.log(blob);  // 新的图片文件信息
          // console.log( URL.createObjectURL(blob) )

          this.$toast.loading({
            forbidClick:true,
            message:'上传中'
          })
          let fd = new FormData()  // 表单数据对象
          // fd.append('接口字段名',数据)
          fd.append('photo',blob)
          try {
            let { data } = await updateUserPhoto(fd)
            this.$toast.success('上传成功')
            this.$emit('update-photo',data.data.photo)
            this.$emit('close')
          } catch (error) {
            return this.$toast.fail('上传失败')
          }
        },'image/png')
      }
  },
  beforeDestroy(){
    this.cropper = null
  }
}
</script>

<style scoped lang="less">
.update-photo {
  background-color: #000;
  height: 100%;
  .toolbar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    justify-content: space-between;
    .cancel, .confirm {
      width: 90px;
      height: 90px;
      font-size: 30px;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
    }
  }
}
.img {
  display: block;
  max-width: 100%;
}
</style>
